#include <stdio.h>
#include <stdlib.h>
#define Data_type int
typedef struct node
{
    Data_type data;
    struct node *next;
} snode, *psnode;

typedef struct stack
{
    int size;
    snode *top;
} stack;

// 链式栈创建
stack *stack_create()
{
    stack *s = (stack *)malloc(sizeof(stack));
    if (s == NULL)
    {
        printf("分配内存失败\n");
    }
    s->size = 0;
    s->top = NULL;
    return s;
}
// 入栈
int stack_push(stack *s, Data_type value)
{
    if (s == NULL)
    {
        printf("栈为空\n");
        return -1;
    }
    psnode newNode = (psnode)malloc(sizeof(psnode));
    if (newNode == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    newNode->data = value;
    newNode->next = s->top;
    s->top = newNode;
    s->size++;
}
// 出栈
psnode stack_pop(stack *s)
{

    if (s == NULL)
    {
        printf("栈为空\n");
        return NULL;
    }
    psnode currentNode = s->top;
    s->top = currentNode->next;
    s->size--;
    printf("%d\n", currentNode->data);
    return currentNode;
}
// 销毁栈
int stack_destory(stack *s)
{

    if (s == NULL)
    {
        printf("栈为空\n");
        return -1;
    }
    psnode currentNode = s->top;
    while (currentNode)
    {
        psnode qnode = currentNode;
        currentNode = currentNode->next;
        free(qnode);
        s->size--;
    }
}
// 查找
psnode stack_get(stack *s, int pos)
{
    if (s == NULL)
    {
        printf("栈为空\n");
        return NULL;
    }
    if (pos > s->size)
    {
        printf("位置错误\n");
        return NULL;
    }
    psnode currentNode = s->top;
    int i = 0;
    while (i < pos)
    {
        currentNode = currentNode->next;
        i++;
    }
    return currentNode;
}
// 修改
int stack_set(stack *s, int pos, Data_type value)
{
    if (s == NULL)
    {
        printf("栈为空\n");
        return -1;
    }
    if (pos > s->size)
    {
        printf("位置错误\n");
        return -1;
    }
    psnode node = stack_get(s, 2);
    node->data = value;
    return 0;
}

void main()
{
    stack *s = stack_create();
    stack_push(s, 1);
    stack_push(s, 2);
    stack_push(s, 3);
    stack_set(s, 0, 987);
    // psnode node = stack_get(s, 0);
    // printf("%d\n", node->data);
    // stack_destory(s);
    while (s->size > 0)
    {
        stack_pop(s);
    }
}